package android.textIt.backend.dao;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import textapp.connector.message.CreateGroupResponse;
import android.content.Context;
import android.database.Cursor;
import android.textIt.backend.Properties;
import android.textIt.backend.database.DBProperties;
import android.textIt.backend.database.DatabaseHelper;
import android.textIt.backend.model.Group;
import android.textIt.backend.model.User;

import com.google.gson.Gson;

public class GroupDao {

  private final DatabaseHelper helper;

  public GroupDao(Context ctx) {
    helper = new DatabaseHelper(ctx);
  }

  public Group getGroupById(long id) {
    Cursor c = helper.getByID(id, DBProperties.GROUP_TABLE);
    if (c.getCount() > 0) {
      return new Group(c);
    }
    else
      return new Group();
  }

  public long createGroup(Group g) {
    return helper.createGroup(g);
  }

  public void updateGroup(Group g) {
    helper.updateGroup(g);
  }

  public List<Group> getAllGroups() {
    Cursor c = helper.getAllEntries(DBProperties.GROUP_TABLE);
    ArrayList<Group> returnList = new ArrayList<Group>();
    if (c.getCount() > 0) {
      do {
        returnList.add(new Group(c));
      }
      while (c.moveToNext());
    }

    return returnList;
  }
  
  public List<Group> getPermanentGroups() {
    Cursor c = helper.getPermanentGroups();
    ArrayList<Group> returnList = new ArrayList<Group>();
    if (c.getCount() > 0) {
      do {
        returnList.add(new Group(c));
      }
      while (c.moveToNext());
    }

    return returnList;
  }

  public void addUsertoGroup(Group g, User u) {
    helper.addUsertoGroup(g.getId(), u.getId());
  }

  public void addUserstoGroup(Group g, List<User> users) {
    // Backend.call(<JSON>);
    for (User u : users)
      helper.addUsertoGroup(g.getId(), u.getId());
  }

  public void removeUserFromGroup(Group g, User u) {
    helper.removeUserFromGroup(u, g);
  }

  public void removeUsersFromGroup(Group g, List<User> users) {
    for (User u : users)
      helper.removeUserFromGroup(u, g);
  }

  public List<User> getUsersInGroup(Group g) {
    Cursor c = helper.getUsersInGroup(g);
    ArrayList<User> returnList = new ArrayList<User>();
    if (c.getCount() > 0) {
      do {
        returnList.add(new User(c));
      }
      while (c.moveToNext());
    }
    return returnList;
  }


  public void registerGroup(Group g) {
    if (!Properties.useServer)
      return;
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(Properties.SERVER_URL + "/createGroupJson");

    try {
      // Add your data
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
      Cursor c = helper.getUsersInGroup(g);
      StringBuilder ids = new StringBuilder();
      if (c.getCount() > 0) {
        do {
          long refId = c.getLong(4); //4 is the reference id
          if(refId!=-1){
            ids.append(Long.toString(refId)+";");
          }
          else{
            ids.append("P"+Long.toString(c.getLong(3))+";"); // 3 is the phone number
          }
        }
        while (c.moveToNext());
      }
      nameValuePairs.add(new BasicNameValuePair("name",g.getName()));
      nameValuePairs.add(new BasicNameValuePair("type","0"));
      nameValuePairs.add(new BasicNameValuePair("owner", Long.toString(helper.getByID(1, DBProperties.USER_TABLE).getInt(4))));
      nameValuePairs.add(new BasicNameValuePair("ids", ids.toString()));

      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

      // Execute HTTP Post Request
      HttpResponse response = httpclient.execute(httppost);
      String returnString = inputStreamToString(response.getEntity().getContent());

      CreateGroupResponse res = new Gson().fromJson(returnString, CreateGroupResponse.class);
      g.setReference_id(res.getBody().getId());
      helper.updateGroup(g);
    

    }
    catch (ClientProtocolException e) {
    }
    catch (IOException e) {
    }
  }

  // Fast Implementation
  private String inputStreamToString(InputStream is) throws IOException {
    String line = "";
    StringBuilder total = new StringBuilder();

    // Wrap a BufferedReader around the InputStream
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

    // Read response until the end
    while ((line = rd.readLine()) != null) {
      total.append(line);
    }

    // Return full string
    return total.toString();
  }

  
}
